import { defineStore } from 'pinia';
import { loginService } from '@/service';
import storage from '@/utils/storage';
import { IUserinfo, Userinfo } from '@/types';
import { getUserinfo, updateUserinfo } from '@/service/userinfo.service';

const useUser = defineStore({
  /** 区分不通状态的唯一标识 */
  id: 'user',
  /** 状态 */
  state: () => ({
    user: {
      mobile: '',
      userGuid: '',
    },
    token: '',
    userinfo: new Userinfo(),
  }),
  actions: {
    async authLogin(code, eventDetail) {
      const { encryptedData, iv } = eventDetail;
      const data = await loginService({
        loginCode: code,
        encryptedData,
        iv,
      });
      this.token = data;
      storage.setItem('token', data);
    },
    async getUserInfo(): Promise<IUserinfo> {
      if (this.userinfo.id) return this.userinfo;
      const token = await storage.getItem('token');
      if (token) {
        this.userinfo = await getUserinfo();
        storage.setItem('userId', this.userinfo.id);
      }
      return this.userinfo;
    },

    async updateUserInfo(params): Promise<void> {
      await updateUserinfo(params);
      this.userinfo = await getUserinfo();
    },
  },
});
export { useUser };
